package com.wego.common.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wego.entity.domain.Order;
import com.wego.entity.domain.User;
import com.wego.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @className: AlipayController
 * @description: TODO 类描述
 * @author: Li Chuanwei
 * @date: 2023/07/18 1:30
 * @Company: Copyright [日期] by [作者或个人]
 **/

@Controller
public class AlipayController {

    @Autowired
    private OrderService orderService;

    @PostMapping(value = "aliPayQuickPay", produces = "text/plain;charset=utf-8")
    public void aliPayQuickPay(String orderNo, String orderAmt,String orderSubject,String businessDesc,HttpServletResponse response) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.appId, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.publicKey, AlipayConfig.signType);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.returnUrl);
        alipayRequest.setNotifyUrl(AlipayConfig.notifyUrl);
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNo +"\","
                + "\"total_amount\":\""+ orderAmt +"\","
                + "\"subject\":\""+ orderSubject +"\","
                + "\"body\":\""+ businessDesc +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //记录日志

        Order order = orderService.selectByPrimaryKey(orderNo);
        order.setState(2);//设置支付成功
        orderService.updateByPrimaryKeySelective(order);

        System.out.println(result);
        response.setContentType("text/html;charset=" + "UTF-8");
        response.getWriter().write(result);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping("returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params.toString());
        boolean signVerified = AlipaySignature.rsaCheckV2(params, AlipayConfig.publicKey, AlipayConfig.charset, AlipayConfig.signType); //调用SDK验证签名

        PrintWriter out = response.getWriter();
        //——请在这里编写您的程序（以下代码仅作参考）——
        User user = (User)session.getAttribute("user");
        Long id = user.getId();
        response.sendRedirect("user_orderDetails?userIds=" + String.valueOf(id));
//        if(signVerified) {
//            //商户订单号
//            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//            //支付宝交易号
//            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//            //付款金额
//            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
//
//            out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
//        }else {
//            out.println("signVerified fail");
//        }
    }
}
